package com.mills.gamebase.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.dao.DataAccessException;
import org.springframework.transaction.annotation.Transactional;

import com.mills.gamebase.dao.IUserDAO;
import com.mills.gamebase.model.User;
import com.mills.gamebase.service.DAO;

/**
 * Implementierung des Interfaces {@linkplain IUserDAO}
 * 
 * @author Shane
 *
 */
public class UserDAO extends AbstractDAO<User> implements IUserDAO {

	public UserDAO() {
		logger = Logger.getLogger(UserDAO.class);
		entityClazz = User.class;
		entityModelName = "User";
	}
	
	@Override
	protected void preload(User entity, String... preloads) {
		for (String preload : preloads) {
			if (preload.equals(PRELOAD_ROLES) || preload.equals(DAO.PRELOAD_ALL)) {
				if (entity.getRoles() != null) entity.getRoles().size();
			}
		}
	}

	@SuppressWarnings("unchecked")
	@Transactional
	public User get(String username, String password, String... preloads) {
		if (logger.isDebugEnabled()) {
			logger.debug("Loading User with username='"+username+"' and password='***'...");
		}
		
		List<User> userList = new ArrayList<User>();
		try {
			userList = (List<User>) sessionFactory.getCurrentSession().createQuery(
						"select u " +
						"from User as u " +
						"where u.username like '" + username + "' " +
						"and u.password like '" + password + "'"
					).list();
		} catch (DataAccessException e) {
			logger.error("Exception caught loading User with username='"+username+"' and password='***' " + e );
		}
		
		if (userList.size() > 0)
		{
			User u = userList.get(0);
			preload (u, preloads);
			return u;
		}
		
		logger.error("No User found with username='"+username+"' and entered password!");
		
		return null;     
	}

	public boolean usernameExists(String username, Long id) {
		if (logger.isDebugEnabled()) {
			logger.debug("Checking existence of username '" + username + "'");
		}
		
		try {
			return sessionFactory.getCurrentSession().createQuery("select u from User as u where u.username like '" + username + "' and u.id != "+ id).list().isEmpty();
		} catch (Exception e) {
			logger.error("Exception caught checking existence of username '" + username + "'!", e);
		}
		
		return false;
	}

}
